import axios, {
    AxiosInstance,
    InternalAxiosRequestConfig,
    AxiosResponse,
} from "axios";
import { useUserStore } from '@/store/user'
import router from '@/router'
import { ElMessage } from "element-plus";

const service: AxiosInstance = axios.create({
    baseURL: "http://127.0.0.1:8000/api",
    timeout: 60000,
    headers: {
        "Content-Type": "application/json",
    },
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 如果有 token 可加在这里
        const userStore = useUserStore()
        let token = userStore.token;
        if (token) config.headers.Authorization = `Bearer ${token}`;
        return config;
    },
    (error) => {
        console.error("请求拦截错误:", error);
        return Promise.reject(error);
    }
);

let isShowingError = false;

service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, error } = response.data;
        const isSuccess = code === 0 || code === 200;

        if (!isSuccess && !isShowingError) {
            isShowingError = true;
            ElMessage.error({
                message: error || "请求失败",
                duration: 1500,
                onClose: () => {
                    isShowingError = false;
                },
            });
            return Promise.reject(new Error(error || "请求失败"));
        }

        return response.data;
    },
    (error) => {
        const userStore = useUserStore();
        if (error.response?.status === 401) {
            const msg =
                error.response?.data?.detail ||    // 这里是后端的详细错误
                error.response?.data?.message ||
                error.response?.data?.error ||
                "网络异常，请稍后再试";
            if (!isShowingError) {
                isShowingError = true;
                ElMessage.error({
                    message: msg,
                    duration: 1500,
                    onClose: () => {
                        isShowingError = false;
                    },
                });
            }
            userStore.logout();
            router.push('/login');
            return Promise.reject(error);
        } else {
            if (!isShowingError) {
                isShowingError = true;
                const msg =
                    error.response?.data?.message ||
                    error.response?.data?.error ||
                    "网络异常，请稍后再试";

                ElMessage.error({
                    message: msg,
                    duration: 1500,
                    onClose: () => {
                        isShowingError = false;
                    },
                });
            }

            return Promise.reject(error);
        }


    }
);

export default service;
